from django.contrib.auth import login
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django.http import JsonResponse

from apps.users.models import User
from meiduo_mall.settings.dev import logger
from utils.response_code import RETCODE
from apps.oauth.models import OAuthQQUser
from utils.secret import SecretOauth


# 判定用户是否绑定了openid
def is_bind_openid(request, openid):
    try:
        qq_oauth = OAuthQQUser.objects.get(openid=openid)

    except Exception as e:
        logger.error(e)

        # 这里对openid进行加密
        secret_openid = SecretOauth().dumps({"openid": openid})

        # 没有绑定的情况,重定向到绑定页面, 并把获取到的openid发送给绑定页面
        content = {
            "openid": secret_openid
        }

        return render(request, "oauth_callback.html", content)
        # 绑定了,就保存登录状态,重定向到首页,设置cookie username用来显示用户名
    else:
        # 绑定完成后,保持登录状态
        qq_user = qq_oauth.user
        login(request, qq_user)

        # 返回响应结果(重定向到首页)
        response = redirect(reverse("contents:index"))
        # 登录时用户名写入到cookie，有效期15天
        response.set_cookie('username', qq_user.username, max_age=3600 * 24 * 15)

        return response


# 2, 获取openid
class QQAuthView(View):
    def get(self, request):
        # 获取路径中的code参数
        code = request.GET.get("code")

        # 构建qq连接对象
        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=" "
        )

        # 获取token
        token = oauth.get_access_token(code)

        # 通过token获取openid
        openid = oauth.get_open_id(token)

        # 判定用户是否绑定了账号
        response = is_bind_openid(request, openid)

        # 返回数据
        # return JsonResponse({"openid获取成功:": openid})
        return response

    # 绑定openid
    def post(self, request):
        # 1.接收参数 form POST
        mobile = request.POST.get('mobile')
        pwd = request.POST.get('password')
        sms_code = request.POST.get('sms_code')
        openid = request.POST.get('openid')

        # 2.校验--判空--正则--短信验证码

        # 3.解密--openid 校验

        openid = SecretOauth().loads(openid).get("openid")
        if not openid:
            return render(request, 'oauth_callback.html', {'openid_errmsg': '无效的openid'})

        # 4.判断用户是否存在 存在 user; 不存在新建user
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            # 不存在 新建user
            user = User.objects.create(username=mobile, password=pwd, mobile=mobile)
        else:
            # 密码不正确
            if not user.check_password(pwd):
                return render(request, 'oauth_callback.html', {'account_errmsg': '用户名或密码错误'})

        # 5.user绑定openid
        try:
            OAuthQQUser.objects.create(openid=openid, user=user)
        except Exception as e:
            return render(request, 'oauth_callback.html', {'qq_login_errmsg': 'QQ登录失败'})

        # 6. 保持登录状态--重定向首页--set_cookie username
        login(request, user)
        response = redirect(reverse('contents:index'))
        response.set_cookie('username', user.username, max_age=24 * 15 * 3600)
        return response


# 1, 获取qq的url
class QQAuthUrlView(View):
    def get(self, request):
        # 1, 构造qq连接对象
        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=" "
        )

        # 2, 获取qq服务器发回来的网页url
        login_url = oauth.get_qq_url()
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'login_url': login_url})
